<!-- templates/chat.html -->

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>Flask 聊天界面</title>
    <style>
        body {
            font-family: 'Arial', sans-serif;
            background-color: #f4f7f6;
            color: #333;
            margin: 0;
            padding: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            position: relative;
        }

        /* 水印样式 */
        #watermark {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            font-size: 100px;
            color: rgba(200, 200, 200, 0.2);
            pointer-events: none;  /* 让水印不可点击 */
            z-index: -1;
            user-select: none;  /* 防止选中 */
        }

        #chat-container {
            width: 500px;
            background-color: #ffffff;
            border-radius: 12px;
            box-shadow: 0px 8px 15px rgba(0, 0, 0, 0.1);
            padding: 20px;
            box-sizing: border-box;
            position: relative;
            z-index: 1;
            display: flex;
            flex-direction: column;
            height: 600px;
        }

        h2 {
            text-align: center;
            color: #555;
            font-weight: 300;
            margin-bottom: 20px;
        }

        /* 控制输出字符长度的容器 */
        #control-container {
            display: flex;
            align-items: center;
            margin-bottom: 10px;
        }

        #max-length-label {
            margin-right: 10px;
            font-weight: bold;
        }

        #max-length-input {
            width: 60px;
            padding: 5px;
            border: 1px solid #ddd;
            border-radius: 6px;
            margin-right: 10px;
            text-align: center;
        }

        #increase-btn, #decrease-btn {
            width: 30px;
            height: 30px;
            border: none;
            border-radius: 50%;
            background-color: #48c78e;
            color: white;
            font-size: 20px;
            cursor: pointer;
            transition: background-color 0.3s ease;
            margin-right: 5px;
        }

        #increase-btn:hover, #decrease-btn:hover {
            background-color: #3db578;
        }

        #messages {
            flex: 1;
            border-radius: 8px;
            border: 1px solid #ddd;
            overflow-y: auto;
            padding: 10px;
            margin-bottom: 15px;
            background-color: #f9f9f9;
            box-shadow: inset 0px 4px 6px rgba(0, 0, 0, 0.05);
            position: relative;
        }

        .message {
            display: flex;
            margin: 10px 0;
            max-width: 80%;
        }

        .message.user {
            align-self: flex-end;
            justify-content: flex-end;
            margin-left: auto; /* 确保靠右 */
        }

        .message.assistant {
            align-self: flex-start;
            justify-content: flex-start;
            margin-right: auto; /* 确保靠左 */
        }

        .message .message-text {
            padding: 10px 15px;
            border-radius: 20px;
            position: relative;
            word-wrap: break-word;
            box-shadow: 0px 3px 6px rgba(0, 0, 0, 0.05);
            max-width: 100%;
        }

        .message.user .message-text {
            background-color: #e6f7ff;
            color: #333;
            border-top-right-radius: 0;
            text-align: right;
        }

        .message.assistant .message-text {
            background-color: #f6ffed;
            color: #333;
            border-top-left-radius: 0;
            text-align: left;
        }

        /* 删除按钮样式 */
        .message .delete-button {
            background-color: #ff6b6b;
            border: none;
            border-radius: 6px;
            color: white;
            padding: 5px 10px;
            cursor: pointer;
            font-size: 12px;
            margin-left: 10px;
            transition: background-color 0.3s ease;
        }

        .message.user .delete-button {
            margin-left: 10px;
        }

        .message.assistant .delete-button {
            display: none;  /* 不显示 AI 回复的删除按钮 */
        }

        .message .delete-button:hover {
            background-color: #ff4c4c;
        }

        #message-input {
            flex: none;
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 6px;
            box-shadow: inset 0px 2px 4px rgba(0, 0, 0, 0.05);
            outline: none;
            box-sizing: border-box;
            margin-bottom: 10px;
        }

        #send-button, #clear-button {
            flex: none;
            width: 100%;
            padding: 10px;
            background-color: #48c78e;
            border: none;
            color: white;
            border-radius: 6px;
            cursor: pointer;
            font-weight: bold;
            transition: background-color 0.3s ease;
            margin-bottom: 10px;
        }

        #send-button:hover {
            background-color: #3db578;
        }

        #clear-button {
            background-color: #ffc107;
        }

        #clear-button:hover {
            background-color: #ffb306;
        }

        /* Scrollbar customization */
        #messages::-webkit-scrollbar {
            width: 8px;
        }

        #messages::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }

        #messages::-webkit-scrollbar-thumb {
            background: #bbb;
            border-radius: 10px;
        }

        #messages::-webkit-scrollbar-thumb:hover {
            background: #888;
        }

        /* 响应式设计 */
        @media (max-width: 600px) {
            #chat-container {
                width: 90%;
                height: 80vh;
            }

            .message {
                max-width: 90%;
            }
        }
    </style>
</head>
<body>
    <!-- 添加水印 -->
    <div id="watermark">昌西</div>

    <div id="chat-container">
        <h2>实时聊天</h2>

        <!-- 控制输出字符长度的功能 -->
        <div id="control-container">
            <label id="max-length-label" for="max-length-input">最大回复字符数：</label>
            <button id="decrease-btn">-</button>
            <input type="number" id="max-length-input" value="500" min="100" max="2000">
            <button id="increase-btn">+</button>
        </div>

        <div id="messages">
            <!-- 消息将动态加载 -->
        </div>
        <input type="text" id="message-input" placeholder="输入消息...">
        <button id="send-button">发送</button>
        <button id="clear-button">清除所有消息</button>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const messagesDiv = document.getElementById('messages');
            const messageInput = document.getElementById('message-input');
            const sendButton = document.getElementById('send-button');
            const clearButton = document.getElementById('clear-button');

            const maxLengthInput = document.getElementById('max-length-input');
            const increaseBtn = document.getElementById('increase-btn');
            const decreaseBtn = document.getElementById('decrease-btn');

            // 加载现有消息
            function loadMessages() {
                fetch('/get_messages')
                    .then(response => response.json())
                    .then(data => {
                        messagesDiv.innerHTML = ''; // 清空当前消息
                        data.messages.forEach(msg => {
                            const msgDiv = document.createElement('div');
                            msgDiv.classList.add('message');
                            msgDiv.classList.add(msg.role); // 添加角色类名

                            const msgText = document.createElement('span');
                            msgText.classList.add('message-text');
                            msgText.textContent = msg.text;

                            msgDiv.appendChild(msgText);

                            if (msg.role === 'user') {
                                const deleteBtn = document.createElement('button');
                                deleteBtn.classList.add('delete-button');
                                deleteBtn.textContent = '删除';
                                deleteBtn.onclick = () => deleteMessage(msg.id);
                                msgDiv.appendChild(deleteBtn);
                            }

                            messagesDiv.appendChild(msgDiv);
                        });
                        messagesDiv.scrollTop = messagesDiv.scrollHeight; // 滚动到底部
                    });
            }

            // 发送消息
            sendButton.addEventListener('click', () => {
                const message = messageInput.value.trim();
                const max_length = maxLengthInput.value.trim();
                if (message !== '') {
                    fetch('/send_message', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            'message': message,
                            'max_length': max_length
                        })
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            messageInput.value = '';
                            loadMessages(); // 重新加载消息
                            // 延迟滚动到底部，等待 AI 回复
                            setTimeout(() => {
                                messagesDiv.scrollTop = messagesDiv.scrollHeight;
                            }, 500);
                        } else {
                            alert('发送失败: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
                }
            });

            // 允许按 Enter 键发送消息
            messageInput.addEventListener('keyup', (event) => {
                if (event.key === 'Enter') {
                    sendButton.click();
                }
            });

            // 删除单条消息
            function deleteMessage(id) {
                fetch('/delete_message', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ 'id': id })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        loadMessages(); // 重新加载消息
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                });
            }

            // 清除所有消息
            clearButton.addEventListener('click', () => {
                if (confirm('确定要清除所有消息吗？')) {
                    fetch('/clear_messages', {
                        method: 'POST'
                    })
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 'success') {
                            loadMessages(); // 重新加载消息
                        } else {
                            alert('清除失败: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                    });
                }
            });

            // 控制输出字符长度的功能
            increaseBtn.addEventListener('click', () => {
                let currentValue = parseInt(maxLengthInput.value);
                if (currentValue < 2000) { // 设置最大值为2000
                    maxLengthInput.value = currentValue + 1;
                }
            });

            decreaseBtn.addEventListener('click', () => {
                let currentValue = parseInt(maxLengthInput.value);
                if (currentValue > 1) { // 设置最小值为100
                    maxLengthInput.value = currentValue - 1;
                }
            });

            // 限制输入框的值在100到2000之间
            maxLengthInput.addEventListener('input', () => {
                let value = parseInt(maxLengthInput.value);
                if (isNaN(value) || value < 1) {
                    maxLengthInput.value = 1;
                } else if (value > 2000) {
                    maxLengthInput.value = 2000;
                }
            });

            // 初始加载消息
            loadMessages();

            // 自动刷新消息，每2秒钟刷新一次
            setInterval(loadMessages, 2000);
        });
    </script>
</body>
</html>